package com.vehiclesecure.controller;

import com.vehiclesecure.model.User;
import com.vehiclesecure.service.UserService;
import com.vehiclesecure.security.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
// import java.util.Optional;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtService jwtService;

    /**
     * 用户注册接口，支持角色选择
     * @param registrationRequest 注册请求包含用户信息
     * @return 注册成功的用户信息和JWT令牌
     */
    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody Map<String, String> registrationRequest) {
        try {
            // 创建用户对象
            User user = new User();
            user.setEmail(registrationRequest.get("email"));
            user.setPassword(registrationRequest.get("password"));
            user.setFirstName(registrationRequest.get("firstName"));
            user.setLastName(registrationRequest.get("lastName"));
            
            // 设置用户角色，默认为USER
            String roleStr = registrationRequest.get("role");
            if (roleStr != null) {
                if (roleStr.equalsIgnoreCase("ADMIN")) {
                    user.setRole(User.Role.ADMIN);
                } else if (roleStr.equalsIgnoreCase("SERVICE_PROVIDER")) {
                    user.setRole(User.Role.SERVICE_PROVIDER);
                } else {
                    user.setRole(User.Role.USER);
                }
            } else {
                user.setRole(User.Role.USER);
            }

            // 注册用户
            User registeredUser = userService.registerUser(user);
            
            // 生成JWT令牌（使用已注册的用户对象）
            String token = jwtService.generateToken(registeredUser);
            
            // 返回用户信息和令牌
            return ResponseEntity.ok(Map.of(
                "user", registeredUser,
                "token", token,
                "message", "用户注册成功"
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 用户登录接口
     * @param loginRequest 登录请求包含邮箱和密码
     * @return 用户信息和JWT令牌
     */
    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody Map<String, String> loginData) {
        try {
            String email = loginData.get("email");
            String password = loginData.get("password");
            String role = loginData.get("role");
            
            if (email == null || password == null || role == null) {
                return ResponseEntity.badRequest().body(Map.of("error", "邮箱、密码和角色不能为空"));
            }
            
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(email, password)
            );
            
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            User user = userService.findByEmail(email)
                .orElseThrow(() -> new UsernameNotFoundException("用户未找到"));
                
            // 验证角色匹配
            if (!user.getRole().name().equals(role)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(Map.of("error", "角色不匹配，请重新选择角色"));
            }
            
            String jwt = jwtService.generateToken(user);
            
            Map<String, Object> response = new HashMap<>();
            response.put("token", jwt);
            response.put("user", user);
            
            return ResponseEntity.ok(response);
            
        } catch (BadCredentialsException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(Map.of("error", "邮箱或密码错误"));
        } catch (UsernameNotFoundException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(Map.of("error", "用户不存在"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("error", "登录失败: " + e.getMessage()));
        }
    }

    /**
     * 用户登出接口
     * @return 成功响应
     */
    @PostMapping("/logout")
    public ResponseEntity<Void> logoutUser() {
        // 在实际应用中，这里可以添加清除服务器端存储的令牌等逻辑
        return ResponseEntity.ok().build();
    }

    /**
     * 获取当前已登录用户信息
     * @return 用户信息
     */
    @GetMapping("/me")
    public ResponseEntity<User> getCurrentUser() {
        // 从SecurityContextHolder获取当前已认证用户的信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userEmail = authentication.getName();
        
        return userService.findByEmail(userEmail)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
}